package com.old.nsi_class.DB;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * 封装信息返回
 * @author 12984
 *
 */
public class JsonResult {	
	
	//没有调用任意方法错误
	private static final int FAULT = -3;
	private static final int ERROR = -2;
	private static final int SUCCESS = 1;
	
	/**
	 * whereFrom无参返回
	 * @param req
	 * @param res
	 * @return -3
	 */
	public static void toResultFault(HttpServletRequest req,HttpServletResponse res) throws IOException {
		String back="{\"msg\":"+FAULT+"}";
		commonMethod(req, res, back);
	}
	
	/**
	 * 页面传参null或者.length()=0
	 * @param req
	 * @param res
	 * @return -2
	 */
	public static void toResultError(HttpServletRequest req,HttpServletResponse res) throws IOException {
		String back="{\"msg\":"+ERROR+"}";
		commonMethod(req, res, back);
	}
	
	/**
	 * 方法成功后返回信息
	 * @param req
	 * @param res
	 * @return 1
	 */
	public static void toResult(HttpServletRequest req,HttpServletResponse res) throws IOException {
		String back="{\"msg\":"+SUCCESS+"}";
		commonMethod(req, res, back);
	}
	
	
	/**
	 * 成功后返回参数
	 * @param req
	 * @param res
	 * @param data
	 */
	public static void toResultString(HttpServletRequest req,HttpServletResponse res,String data) throws IOException {
		String back="{\"code\":0,\"msg\":"+SUCCESS+",\"data\":\""+data+"\"}";
		commonMethod(req, res, back);
	}
	
	/**
	 * 成功后返回
	 * @param req
	 * @param res
	 * @param data
	 */
	public static void toResult(HttpServletRequest req,HttpServletResponse res,int count,String data) throws IOException {

		String back="{\"code\":0,\"msg\":"+SUCCESS+",\"count\":"+count+",\"data\":"+data+"}";
		commonMethod(req, res, back);
	}
	
	/**
	 * 方法成功后返回活动系统json数据
	 * @param req
	 * @param res
	 * @param gson 
	 * @return json 
	 */
	public static void toResult(HttpServletRequest req,HttpServletResponse res,Gson gson,List<?> list) throws IOException {
		String jsonList = gson.toJson(list);

		String back="{\"code\":"+SUCCESS+",\"data\":"+jsonList+"}";
		commonMethod(req, res, back);
	}
	
	/**
	 * 方法成功后返回活动系统json数据
	 * @param req
	 * @param res
	 * @param gson 
	 * @return json 
	 */
	public static void toResult(HttpServletRequest req,HttpServletResponse res,Gson gson,List<?> data1,List<?> data2) throws IOException {
		String jsonList1 = gson.toJson(data1);
		String jsonList2 = gson.toJson(data2);
		String back="{\"msg\":"+SUCCESS+",\"data1\":"+jsonList1+",\"data2\":"+jsonList2+"}";

		commonMethod(req, res, back);
	}
	
	/**
	 * 通用调用方法
	 * @param req
	 * @param res
	 * @param back
	 * @throws IOException
	 */
	public static void commonMethod(HttpServletRequest req, HttpServletResponse res, String back) throws IOException {
		res.setContentType("application/json;charset=UTF-8");  
		res.getWriter().write(back);
	}
	
	
}
